/* read.phtml JS  */

$(function () {
	xindm.init(dataObj);
});

var xindm = {
	server: '', //'http://www.chuiyao.com/manhua/',
	serverTime: '',
	DATA: {}, volDATA: null, comicName: '', maxWidth: 0, nextVolNum: 0, loadFlag: true, tipsFlag: true, volCACHE: [], timeDiff: false, volSort: 1,
	/* 初始化 */
	init: function(dataObj) {
		var s = this;
		$(window).delay(100).queue(function() {
			s.server = dataObj.hostComicUrl;
			s.serverTime = dataObj.serverTime;
			s.band();
			s.dealData('get');
			s.makeVolHtml();
		});
	},
	/* 卷集/图片 数据管理 */
	dealData: function(_flag) {
		var s = this;    
		var timenow = s.getTimenow();
		var flag = typeof _flag != 'undefined' && _flag == 'save' ? 'save' : 'get';
		if (flag == 'get') {
			s.comicName = s._getComicName();
			s.DATA = s.dataMgr('DATA');
			if (typeof s.DATA.history != 'object') {
				alert('未找到卷集数据');
				die();
				return false;
			}
			var item = s.DATA.history[s.comicName] || false;
			if (item == false) {
				var flag = s.showVols(s.comicName);
				if (!flag) {
					alert('卷集[' + s.comicName + ']数据获取失败,请尝试刷新');
					$('#comic_title').text('请尝试刷新页面！');
					die();
					return false;
				}
				return true;
			}
			s.volDATA = item;
			s.volDATA.pics = typeof s.volDATA.pics != 'undefined' && timenow - s.volDATA.time < 3600 * 24 * 5 ? s.volDATA.pics : []; // 卷集图片初始化
			s.volDATA.read = s.volDATA.read || {}; // 已阅读卷集初始化
		} else {
			s.volDATA.time = timenow;
			s.DATA = s.dataMgr('DATA');
			s.volDATA.status = s.DATA.status;
			s.DATA.history[s.comicName] = s.volDATA;
			s.dataMgr('DATA', s.DATA);
		}
	},
	/* 获取卷集列表 */
	showVols: function(_comicName) {
		var s = this;
		var comicName = _comicName || s.comicName;
		var time = s.getTimenow();
		var comic = s.DATA.comic;
		// 官网获取
		var url = '?a=showVols&comicName=' + comicName;
		s.showTips('正在获取卷集信息，请稍后···'); // 获取动画
		var data = s.AJAX(url);
		s.showTips();
		$.ajaxSettings.async = false; // 同步请求数据
		//$.getJSON(url, function(data) {
			
			if (typeof data.status == 'undefined') {
				alert('获取结果失败~~');
				return false;
			}
			if (data.status == 'true') {
				s.DATA.comic[comicName] = s.DATA.comic[comicName] || {};
				s.DATA.comic[comicName] = $.extend({}, s.DATA.comic[comicName], data); // 缓存数据
				s.saveVol(data.lists, comicName, decodeURIComponent(data.title));
				return true;
			} else if (data.status == 'false') {
				alert('获取列表失败~~');
				return false;
			} else {
				alert('未知错误');
				return false;
			}
		//});
		console.log('async test');
	},
	/* 存储历史记录 */
	saveVol: function(_listArr, comicName, comicTitle) {
		var listArr = _listArr || null;
		if (typeof listArr != 'object' || listArr == null) {
			console.log('listArr is null');
			return false;
		}
		var s = this;
		s.DATA = s.dataMgr('DATA');
		var timenow = s.getTimenow();
		//var comicTitle = s.comicTitle;
		var _item = {"status": "1", "title": comicTitle, "comicName": comicName, "list": [], "rtime": 0, "pics": [], "read": [], "time": 1};
		//判断是否是数组还是对象..
		s.DATA.history[comicName] = s.DATA.history[comicName] || _item;
		s.DATA.history[comicName].list = listArr;
		s.DATA.history[comicName].rtime = (new Date()).Format("yyyy-MM-dd");
		s.DATA.history[comicName].time = timenow;
		s.dataMgr('DATA', s.DATA);
		
		s.volDATA = s.DATA.history[comicName];
		s.volDATA.pics = typeof s.volDATA.pics != 'undefined' && timenow - s.volDATA.time < 3600 * 24 * 5 ? s.volDATA.pics : [];
		s.volDATA.read = s.volDATA.read || {};
	},
	/* Ajax */
	AJAX: function(url, post) {
		if (typeof url == 'undefined' || url == '') {
			return false;
		}
		var post = typeof post != 'object' ? post : null;
		var method = post == null ? 'GET' : 'POST';
		var ajax = $.ajax({
			"type": method,
			"url": url,
			"data": post,
			"dataType": 'text',
			"timeout": 15000,
			"async": false,
			"cache": false,
			"success": function (_data) {
				return false;
			}
		});
		if (ajax.status != '200') {
			alert('请求数据失败，请重试~');
			return false;
		}
		return JSON.parse(ajax.responseText); // test
		try {
			var json = JSON.prese(ajax.responseText);
		} catch (err) {
			//var msg = '错误：' + err.message + '\n获取数据失败';
			console.log('【' + ajax.responseText + '】');
		}
		return json;
	},
	/* 数据存储管理 */
	dataMgr: function(_name, _data) {
		var data = _data || null;
		var name = _name || null;
		if (_name == null) {
			return false;
		}
		if (data == null) {
			var item = localStorage.getItem(name);
			return JSON.parse(item);
		} else {
			var itemStr = JSON.stringify(data);
			localStorage.setItem(name, itemStr);
			console.log(name + ' save !');
		}
	},
	/* 刷新卷集 */
	updateVols: function() {
		var s = this;
		var flag = s.showVols(s.comicName);
		if (flag) {
			s.makeVolHtml();
			alert('刷新卷集成功');
		} else {
			alert('刷新卷集失败,请尝试重试');
		}
	},
	/* 组装卷集html */
	makeVolHtml: function() {
		var s = this;
		var data = s.volDATA;
		$('#comic_title').html(data.title).attr('href', s.server + s.comicName + '/');
		var total = 0, item, volTemp, volArr = new Array();
		for (var i in data.list) {
			++total;
			item = data.list[i];
			volTemp = '<div class="volTemp" title="' + item.volName + '" vol="' + item.vol + '">' + total + '. ' + item.volName + '</div>';
			volArr.push(volTemp);
		}
		if (s.volSort == 2) {
			volArr.reverse();
		}
		var volHtml = volArr.join("\n");
		$('#vols').html(volHtml);
		s.readAction();
	},
	/* 事件绑定 */
	band: function() {
		var s = this;
		$(document).on('click', '.update_vols, .volTemp, .close, .tips_cancle', function(event) {
			var _class = $(this).attr('class');
			switch (_class) {
				case 'close':
					s.bgSwitch('on');
					break;
				case 'volTemp':
					var vol = $(this).attr('vol');
					s.readVol(vol);
					break;
				case 'tips_cancle':
					s.showTips();
					break;
				case 'update_vols':
					s.updateVols();
					break;
				default:
					break;
			}
		});
		$(document).on('click', '[data-sort]', function() {
			var $dom = $(this);
			var sort = $dom.data('sort');
			if (s.volSort == sort) {
				return false;
			}
			$('#sort-box button').removeClass('selected');
			$dom.addClass('selected');
			s.volSort = sort;
			s.makeVolHtml();
		});
	},
	/* 获取漫画图片 */
	readVol: function(_vol) {
		var s = this;
		var vol = _vol - 0 + 1;
		if ($('[vol="' + _vol + '"]').length < 1) {
			console.log('vol not be found..') + alert('已经是最后一卷/集');
			return false;
		}
		s.nextVolNum = vol;
		var url = '?a=readVol&t=any&n=' + s.volDATA.comicName + '&rids[]=' + vol;
		s.getPicData(url, _vol);
	},
	/* 获取图片url数据 */
	getPicData: function(url, _vol) {
		var s = this, data;
		if (typeof s.volDATA.pics[_vol] == 'object' && s.volDATA.pics[_vol] != null) {
			data =  s.volDATA.pics[_vol];
			s.tipsFlag = true;
			s.dealImg(data, _vol);
			return true;
		}
		s.loadFlag = false;
		s.showTips('卷集加载中 ');
		//die();
		$.get(url, function(_data) {
			s.loadFlag = true;
			var data = eval('(' + _data + ')');
			if (typeof data != 'object') {
				alert('获取卷集图片失败~~');
				return false;
			}
			s.volDATA.pics[_vol] = data;
			s.dealData('save');
			//s.volCACHE[vol] = data;
			s.dealImg(data, _vol);
			s.showTips();
		});
	},
	/* 图片处理 */
	dealImg: function(data, _vol) {
		var s = this;
		if (s.tipsFlag == false) {
			return false;
		}
		var temp, imgTemp, imgArr = [];
		//s.maxWidth = s.maxWidth > 0 ? s.maxWidth : document.documentElement.clientWidth - 20;
		for (var i in data) {
			temp = data[i];
			imgTemp = '<div class="pic-box"><img class="comic-img" src="' + temp + '" /></div>'; // style="max-width: ' + s.maxWidth + 'px"
			imgArr.push(imgTemp);
		}
		var imgHtml = imgArr.join("\n");
		$('#readVolName').html($('[vol="' + _vol + '"]:eq(0)').html());
		$('#picContents').html(imgHtml);
		s.readAction(_vol);
		s.bgSwitch('off');
	},
	/* 已阅读标记 */
	readAction: function(vol) {
		var s = this;
		var timenow = s.getTimenow();
		var _vol = vol || null;
		if (_vol != null) {
			s.volDATA.read[_vol] = true;
			s.volDATA.rtime = (new Date()).Format("yyyy-MM-dd");
			s.volDATA.time = timenow;
			s.dealData('save');
		}
		for (var i in s.volDATA.read) {
			if (s.volDATA.read[i] == true) {
				$('[vol="' + i + '"]').attr('read', '1');
			}
		}
	},
	/* 下一卷集 */
	nextVol: function(_flag) {
		var s = this;
		if (s.loadFlag == false) {
			console.log('loading, wait.');
			return false;
		}
		var flag = _flag == 'prev' ? 'prev' : 'next';
		var volNum = flag == 'prev' ? s.nextVolNum - 2 : s.nextVolNum;
		if (volNum < 0) {
			console.log('first vol..') + alert('已经是第一卷/集');
			return false;
		}
		s.readVol(volNum);
	},
	/* tips */
	showTips: function(_str) {
		var s = this;
		var str = typeof _str != 'undefined' ? _str : false;
		if (str == false) {
			s.tipsFlag = false;
			$('.tips').hide();
			return false;
		}
		s.tipsFlag = true;
		$('.tips_cont:eq(0) span').html(str);
		$('.tips').show();
		return false;
	},
	/* 背景切换 */
	bgSwitch: function(_type) {
		var type = typeof _type && _type == 'off' ? 'off' : 'on';
		if (type == 'off') {
			$('body:eq(0)').css('background', '#000');
			$('#comic_title').css('color', '#fff');
			$('#vols, #sort-box').hide();
			$('#picView').show();
			window.scrollTo(0, 0); // 返回顶部
		} else {
			$('body:eq(0)').css('background', '#fff');
			$('#comic_title').css('color', '#000');
			$('#picView').hide();
			$('#vols, #sort-box').show();
		}
	},
	/* 获取漫画名 */
	_getComicName: function() {
		var name = 'n';
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return unescape(r[2]);
		return null;
	},
	/* 获取时间戳 */
	getTimenow: function() {
		var s = this;
		var _timenow = Math.round(new Date().getTime() / 1000);
		if (s.timeDiff === false) {
			s.timeDiff = -(_timenow - s.serverTime);
		}
		var timenow = _timenow + s.timeDiff;
		return timenow;
	}
};


// 日期格式化
Date.prototype.Format = function(fmt) { //author: meizz
	// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
	// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
	var o = {
		"M+": this.getMonth() + 1,
		//月份   
		"d+": this.getDate(),
		//日   
		"h+": this.getHours(),
		//小时   
		"m+": this.getMinutes(),
		//分   
		"s+": this.getSeconds(),
		//秒   
		"q+": Math.floor((this.getMonth() + 3) / 3),
		//季度   
		"S": this.getMilliseconds() //毫秒   
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}